<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 角色列表展示 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <el-row
              :class="['bdbuttom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scoped.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  v-if="item1.children.length != 0"
                  closable
                  @close="removeRightsById(scoped.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i
                  v-if="item1.children.length != 0"
                  class="el-icon-caret-right"
                ></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      v-if="item2.children.length != 0"
                      closable
                      @close="removeRightsById(scoped.row, item2.id)"
                      type="success"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i
                      v-if="item2.children.length != 0"
                      class="el-icon-caret-right"
                    ></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      :class="[i3 === 0 ? '' : 'bdtop']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="removeRightsById(scoped.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column
          type="index"
          label="编号"
          width="49px"
        ></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="360px">
          <template slot-scope="scoped">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRole(scoped.row)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(scoped.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showRights(scoped.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <!-- 添加角色弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialogVisible"
      widtf="50%"
      @close="closeDialog"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="roleForm"
        :rules="roleFormRules"
        ref="roleFormRef"
        label-width="80px"
        status-icon
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 分匹配权限弹框 -->
    <el-dialog
      :visible.sync="setRightDialogVisible"
      title="分配权限"
      width="50%"
      @close="closeRightDialog"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="treeRef"
        highlight-current
        :props="treeProps"
        :default-checked-keys="defaultCheck"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    //获取所有角色
    this.getRoleList()
  },
  data() {
    return {
      //角色列表
      roleList: [],
      //添加角色弹框
      addDialogVisible: false,
      //添加角色表单
      roleForm: {
        roleName: '',
        roleDesc: ''
      },
      //添加角色验证规则
      roleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 8, message: '名称长度在3~8个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 16, message: '名称长度在3~16个字符', trigger: 'blur' }
        ]
      },
      //添加修改角色的标题
      title: '添加角色',
      //记录要编辑角色的id
      roleId: '',
      //控制分配权限弹框
      setRightDialogVisible: false,
      //权限列表
      rightsList: [],
      //树形控件的绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //默认勾选的权限的id数组
      defaultCheck: [],
      //要修改权限,分配权限的角色id
      roleRightId: ''
    }
  },
  methods: {
    //获取角色列表
    async getRoleList() {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res);
      this.roleList = res.data
    },
    //添加修改角色
    addRole() {
      if (this.title == '修改角色') {
        this.$refs.roleFormRef.validate(async valid => {
          //预校验表单
          if (valid) {
            //通过校验
            const res = await this.$http.put(
              'roles/' + this.roleId,
              this.roleForm
            )
            if (res.meta.status !== 200)
              return this.$message.error(res.meta.msg)
            //修改成功
            this.$message.success(res.meta.msg)
            //把弹框隐藏
            this.addDialogVisible = false
            //把标题修改为添加角色
            this.title = '添加角色'
            //重置弹框
            this.closeDialog()
            //重新获取角色列表
            this.getRoleList()
          }
        })
      } else {
        //title为添加角色，就是添加操作
        //进行添加预校验
        this.$refs.roleFormRef.validate(async valid => {
          if (valid) {
            //通过校验
            const res = await this.$http.post('roles', this.roleForm)
            console.log(res)
            if (res.meta.status !== 201)
              return this.$message.error(res.meta.msg)
            //添加成功
            this.$message.success(res.meta.msg)
            //关闭添加弹框
            this.addDialogVisible = false
            //重置表单
            this.closeDialog()
            //重新获取角色列表
            this.getRoleList()
          }
        })
      }
    },
    //关闭添加角色弹框后重置表单
    closeDialog() {
      //重置校验结果
      this.$refs.roleFormRef.resetFields()
      //把title改为添加角色
      this.title = '添加角色'
      //清空表单内容
      this.roleForm.roleName = ''
      this.roleForm.roleDesc = ''
    },
    //删除角色
    deleteRole(id) {
      this.$MessageBox
        .confirm('此操作将永久删除该角色，是否继续', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const res = await this.$http.delete('roles/' + id)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          //删除成功
          this.$message.success(res.meta.msg)
          //重新获取角色列表
          this.getRoleList()
        })
        .catch(() => {
          this.$message.info('取消删除操作')
        })
    },
    //获取要编辑用角色的内容
    async editRole(role) {
      //获取要修改角色的内容
      const res = await this.$http.get('roles/' + role.id)
      //把获取过来的内容赋给角色表单
      this.roleForm = res.data
      //把弹框标题改为修改角色
      this.title = '修改角色'
      //显示修改弹框
      this.addDialogVisible = true
      //把要修改角色的id存储起来以便做修改
      this.roleId = role.id
    },
    //根据角色id和权限id删除权限
    removeRightsById(role, rightId) {
      this.$MessageBox
        .confirm('此操作将永久删除该权限，是否继续', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          const res = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          //取消权限成功
          this.$message.success(res.meta.msg)
          //把返回的最新的权限数据赋值给对应的role
          role.children = res.data
        })
        .catch(() => this.$message.info('删除操作已取消。'))
    },
    //点击分配权限按钮获取权限数据
    async showRights(role) {
      //获取所有权限列表
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      // 获取成功
      //this.$message.success(res.meta.msg)
      //把返回的数据给权限列表
      this.rightsList = res.data
      //把默认的权限赋给默认勾选的权限的id数组
      this.getLeafKeys(role, this.defaultCheck)
      //把要修改权限角色的id存储起来以便修改操作
      this.roleRightId = role.id
      this.setRightDialogVisible = true
    },
    //通过递归的形式获取三级权限的id并保存到defaultCheck中
    getLeafKeys(node, arr) {
      //如果当前的node节点不包含children属性，证明是三级权限
      if (!node.children) {
        //把三级权限的id值存储进数组
        return arr.push(node.id)
      }

      //如果还有children属性,继续调用
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    //监听分配权限弹框关闭事件
    closeRightDialog() {
      //把默认勾选的id数组重置
      this.defaultCheck = []
    },
    //修改分配权限
    async modifyRights() {
      //获取选中权限的id
      const fullChecks = this.$refs.treeRef.getCheckedKeys()
      //获取半选中状态权限的id
      const halfChecks = this.$refs.treeRef.getHalfCheckedKeys()

      //利用展开运算符合并成一个数组
      const keys = [...fullChecks, ...halfChecks]
      const str = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleRightId}/rights`, {
        rids: str
      })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败')
      //修改成功
      this.$message.success(res.meta.msg)
      //重新获取权限列表
      this.getRoleList()
      //清空弹框的数据
      this.closeRightDialog()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbuttom {
  border-bottom: 1px solid #eee;
}
i {
  margin-left: 6px;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
